/**
 * Created by cr. on 2017/8/29.
 * 用于捕获所有从request到response之间发生的异常
 */
const logger = require('lib/logger');

function* error(next) {

    let errResponse = err => {
        let { messageCode, i18n } = err,
        language = this.language || 'zh-CN'; //暂时默认中文
        err.url = err.url || this.request.url;

        if (messageCode) { //系统handle的错误
            // err.message = messageCode;
            err.message = [i18n[language], i18n['extra']].join('');
            delete err.messageCode;
        }

        //非handle错误
        this.body = this.fail(err.message, err.code);
        logger.error(err);
    };

    try {
        yield next;
    } catch (err) {
        errResponse(err); //业务错误
    };
};

module.exports = error;